package org.zfm.org.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zfm.org.domain.Employee;
import org.zfm.org.query.EmployeeQuery;
import org.zfm.org.service.IEmployeeService;
import org.zfm.util.AjaxResult;
import org.zfm.util.PageData;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/employee")
@Api(tags = "员工管理")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @GetMapping
    @ApiOperation(value = "查询所有员工")
    public AjaxResult getAll(){
        try {
            List<Employee> employeeList = employeeService.selectAll();
            return AjaxResult.getBean().setResult(employeeList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getBean().setSuccess(false).setMessage("查询失败"+e.getMessage());
        }
    }

    @PostMapping
    @ApiOperation(value = "分页/高级查询数据")
    public AjaxResult getPageData(@RequestBody EmployeeQuery query){
        try {
            PageData<Employee> pageData = employeeService.queryPageData(query);
            return AjaxResult.getBean().setResult(pageData);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getBean().setSuccess(false).setMessage(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单条数据")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.getBean();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getBean().setSuccess(false).setMessage(e.getMessage());
        }
    }

    @PutMapping
    @ApiOperation(value = "新增/修改")
    public AjaxResult save(@RequestBody Employee employee){
        try {
            if(Objects.isNull(employee.getId())){
                employeeService.insert(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.getBean();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getBean().setMessage(e.getMessage()).setSuccess(false);
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除")
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            employeeService.batchDelete(ids);
            return AjaxResult.getBean();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.getBean().setSuccess(false).setMessage(e.getMessage());
        }
    }
}
